package easier.app.x.result;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Process;
import androidx.activity.result.ActivityResultCallback;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.PermissionChecker;
import androidx.fragment.app.FragmentManager;
import java.util.Map;

/**
 * 简化请求权限
 * registerForActivityResult需要在start状态之前创建,所以使用{@link ResultFragment}辅助
 */
public class Permission {

    /**
     * @param context    检查权限
     * @param permission 需要检查的权限
     *
     * @return true:有权限
     */
    public static boolean check( Context context, String permission ) {

        if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ) {

            return ContextCompat.checkSelfPermission( context, permission ) == PackageManager.PERMISSION_GRANTED;
        } else {
            return PermissionChecker.checkPermission( context, permission, Process.myPid(), Process.myUid(),
                context.getPackageName() ) == PermissionChecker.PERMISSION_GRANTED;
        }
    }

    /**
     * 检查是否有勾选了对话框中”Don’t ask again”的选项
     *
     * @param activity   Activity
     * @param permission 权限
     *
     * @return ture:勾选了
     */
    public static boolean shouldShowRequestPermissionRationale( Activity activity, String permission ) {

        return ActivityCompat.shouldShowRequestPermissionRationale( activity, permission );
    }

    /**
     * 请求权限
     *
     * @param manager    activity
     * @param permission 权限
     * @param callback   回调
     */
    public static void registerForPermissionResult(
        FragmentManager manager,
        String permission,
        ActivityResultCallback< Boolean > callback ) {

        ResultFragment< String, Boolean > fragment = ResultFragmentFactory.buildPermission( permission, callback );
        manager.beginTransaction().add( fragment, "PermissionFragment" ).commit();
    }

    /**
     * 请求权限
     *
     * @param manager     activity
     * @param permissions 多个权限
     * @param callback    回调
     */
    public static void registerForPermissionsResult(
        FragmentManager manager,
        String[] permissions,
        ActivityResultCallback< Map< String, Boolean > > callback ) {

        ResultFragment< String[], java.util.Map< String, Boolean > > f = ResultFragmentFactory.buildPermissions(
            permissions,
            callback
        );
        manager.beginTransaction().add( f, "PermissionsFragment" ).commit();
    }
}
